<template>
    <div>
        <input type="text" placeholder="账号" v-model="user.account">
        <input type="text" placeholder="密码" v-model="user.password">
    </div>
    <div>
        <button @click="Login">登录</button>
        <!-- 一个选择框 -->
        <n-checkbox v-model:checked="user.remember" label="七天免登录"></n-checkbox>
    </div>
</template>

<script setup>
import { reactive, ref, inject, onMounted } from 'vue';
import { epStore } from "../common/store.js";
import { storeToRefs } from "pinia";
import { NCheckbox } from "naive-ui"
import TopNav from "./TopNav.vue"
import { useRouter, useRoute } from 'vue-router'

const axios = inject("axios")
const user = reactive({
    account: !localStorage.getItem("USER_ACCOUNT") ? localStorage.getItem("LOGIN_REMEMBER") : null,
    password: null,
    token: !localStorage.getItem("TOKEN") ? localStorage.getItem("TOKEN") : null,
    remember: false,
})
const store_data = epStore()
const router = useRouter()

const Login = async () => {
    let res = await axios.post(
        "/login/",
        {
            user_account: user.account,
            user_password: user.password
        }
    )
    if (!res.headers.authorization) {
        console.log("登录失败");
        if (res.data.code === 401) {
            console.log("请注册");
            // 跳转到注册页面、注册路由
            return ;
        }
        console.log("未知错误");
        return ;
    } else{
        store_data.token = res.headers.authorization;
        store_data.user_account = user.account;

        // console.log(res.headers.authorization);

        if (user.remember) {
            // 本地储存
            localStorage.setItem('USER_ACCOUNT', store_data.user_account);
            localStorage.setItem('TOKEN', store_data.token);
        } else {
            localStorage.setItem('USER_ACCOUNT', store_data.user_account);
        }

        localStorage.setItem('LOGIN', true);

        await router.push("/panel");
    }
}


</script>

<style lang="scss" scoped>

</style>